<?php

/**
 * <li>Title: user.php</li>
 * <li>Project: kick note</li>
 * <li>Package: /app/models/User</li>
 * <li>Description: models of user's validation </li>
 * <li>Copyright: Copyright (c) 2008</li>
 * <li>Company: Infolex LLC </li>
 * <li>Created on 2008-5-13</li>
 *
 * @author lei_gao
 * @version 1.0
 */
require_once(APP.'libs'.DS.'system_properties.php');
App::import('Vendor','/infolex/app_config');
class User extends AppModel
{
	var $name='User';
	var $validate = array();


	function addUserMoney($uid, $money) {
	    $uid = intval($uid);
	    $money = intval($money);
	    $sql = "update g_users set g_money = g_money +($money) where g_id = {$uid}";
	    	    echo $sql;
	    $data = $this->query($sql);

	    
	}
	function showmj($uid) {
	    $sql = 'SELECT `g_ip` FROM `g_users` WHERE `g_uid` ='.intval($uid);
	    $data = $this->query($sql);
	    if (empty($data[0]['g_users']['g_ip'])) {
	        return array();
	    } 
	    $sql = "SELECT `g_uid`,`g_ip` FROM `g_users` WHERE `g_ip`  LIKE  '{$data[0]['g_users']['g_ip']}'";
	    $data = $this->query($sql);
	    if (empty($data)) {
	        return array();
	    } else {
	        return $data;
	    }
	    
	}
	function viewUerInfo($uid){
		$data=$this->findAll(array('User.g_uid'=>$uid),array('g_uid','g_name','g_money','g_head','g_message','g_login_time'),'User.g_id');
		return $data;
	}
	function findCounts($name=null,$g_id=null, $realname = null){
		$querySql="1=1 ";
		if (!empty($realname)) {
		    $querySql.="and g_realname like '%$realname%' ";
		}
		if(!empty($name)){
			$querySql.="and g_name like '%$name%' ";
		}
		if(!empty($g_id)){
			$querySql.="and g_uid=$g_id ";
		}
		$data=$this->query("select count(1) from  g_users  where $querySql");
		return $data[0][0]['count(1)'];
	}
	function getUserInfo($perPage,$name=null,$g_id=null,$realname=null,$order=0){
		$querySql="1=1 ";
		if (!empty($realname)) {
		    $querySql.="and g_realname like '%$realname%' ";
		}
		if(!empty($name)){
			$querySql.="and g_name like '%$name%' ";
		}
		if(!empty($g_id)){
			$querySql.="and g_uid=$g_id ";
		}
		$number=SystemProperties::$user_message_number;
		if ($order==0){
			$querySql.=" order by g_money desc , g_add_time limit $perPage,$number";
		}else if ($order==1){
			$querySql.=" order by g_add_time desc limit $perPage,$number";
		}
		$user_info=$this->query("select * from  g_users  where $querySql");
		return $user_info;
	}

	
	function listApplyOKCount(){
		$table = SystemProperties::get_table_name('g_apply',1);
		$data=$this->query("select count(1) from  $table  where g_status=1");
		return $data[0][0]['count(1)'];
	}
	function listChangeOKCount(){
		$table = SystemProperties::get_table_name('g_exchange',1);
		$data=$this->query("select count(1) from  $table ");
		return $data[0][0]['count(1)'];
	}
	
	function searchUserByWhere($where) {
	    $where = mysql_escape_string($where);
	    $sql = "SELECT * FROM `g_users` WHERE `g_address` LIKE '%{$where}%' OR `g_province` LIKE '%{$where}%' OR `g_city` LIKE '%{$where}%'";
	    $data = $this->query($sql);
	    return $data;
	}
	function listApplyOK($curPage,$perPage,$user_name = ''){
		$table = SystemProperties::get_table_name('g_apply',1);
		$start = ($curPage-1)*$perPage;
		$user_name = mysql_escape_string($user_name);
		
		$time_start = empty($_REQUEST['from'])?0:intval($_REQUEST['from']);
		$time_end = empty($_REQUEST['end'])?0:intval($_REQUEST['end']);
		if (!empty($time_start) && !empty($time_end)){
		    $t_s = date('Y-m-d',$time_start);
		    $t_e = date('Y-m-d',$time_end);
		    $where_date = " `$table`.`g_time` >'$t_s' and `$table`.`g_time` <'$t_e' ";
		}else {
		    $where_date = ' 1 ';
		}

		
		
		if (empty($user_name)) {
		  $data=$this->query("select * from  $table left join `g_users` on `g_users`.`g_id` = `$table`.`user_id` left join `g_products` on `g_products`.`g_id` = `$table`.`product` where $table.g_status=1 and $where_date limit $start,$perPage");
		} else {
		  $data=$this->query("select * from  $table left join `g_users` on `g_users`.`g_id` = `$table`.`user_id` left join `g_products` on `g_products`.`g_id` = `$table`.`product` where $table.g_status=1 and (`g_users`.`g_realname` = '$user_name' or `g_users`.`g_name` = '$user_name' or `g_users`.`g_uid` = '$user_name') limit $start,$perPage");
		}
		return $data;
	}

	function listChangeOK($curPage,$perPage,$user_name = ''){
		$table = SystemProperties::get_table_name('g_exchange',1);
		$start = ($curPage-1)*$perPage;
		$user_name = mysql_escape_string($user_name);

		$time_start = empty($_REQUEST['from'])?0:intval($_REQUEST['from']);
		$time_end = empty($_REQUEST['end'])?0:intval($_REQUEST['end']);
		if (!empty($time_start) && !empty($time_end)){
		    $t_s = date('Y-m-d',$time_start);
		    $t_e = date('Y-m-d',$time_end);
		    $where_date = " `$table`.`g_time` >'$t_s' and `$table`.`g_time` <'$t_e' ";
		}else {
		    $where_date = ' 1 ';
		}
		
		
		if (empty($user_name)) {
    		$data=$this->query("select * from  $table left join `g_users` on `g_users`.`g_id` = `$table`.`user_id` left join `g_changes` on `g_changes`.`g_id` = `$table`.`product` where $where_date limit $start,$perPage");
		} else {
    		$data=$this->query("select * from  $table left join `g_users` on `g_users`.`g_id` = `$table`.`user_id` left join `g_changes` on `g_changes`.`g_id` = `$table`.`product` where (`g_users`.`g_realname` = '$user_name' or `g_users`.`g_name` = '$user_name' or `g_users`.`g_uid` = '$user_name') limit $start,$perPage");
		}
		return $data;
	}

	function findApplyCounts($user_id){
		//$table="g_apply".$user_id%100;
		$table = SystemProperties::get_table_name('g_apply',$user_id);
		$data=$this->query("select count(1) from  $table  where user_id=$user_id");
		return $data[0][0]['count(1)'];
	}
	function getApplyInfo($user_id,$perPage){
		//$table="g_apply".$user_id%100;
		$table = SystemProperties::get_table_name('g_apply',$user_id);
		$number=SystemProperties::$user_history_number;
		$data=$this->query("select g_id,product,g_img,g_time,g_message,g_jiazhi,remark,user_id from  $table apply where user_id=$user_id limit $perPage,$number");
		//echo "select g_id,product,g_img,g_time,g_message,g_jiazhi,remark,user_id from  $table apply where user_id=$user_id limit $perPage,$number";
		return $data;
	}
	function findExchangCounts($user_id){
		$table = SystemProperties::get_table_name('g_exchange',$user_id);
		//$table="g_exchange".$user_id%100;
		$data=$this->query("select count(1) from  $table  where user_id=$user_id");
		return $data[0][0]['count(1)'];
	}
	function getExchangInfo($user_id,$perPage){
		//$table="g_exchange".$user_id%100;
		$table = SystemProperties::get_table_name('g_exchange',$user_id);
		$number=SystemProperties::$user_history_number;
		$data=$this->query("select g_id,product,g_img,g_time,g_message,g_jiazhi,remark,user_id from  $table apply where user_id=$user_id limit $perPage,$number");
		return $data;
	}
	function updatApplyMark($user_id,$g_id,$name){
		//$table="g_apply".$user_id%100;
		$table = SystemProperties::get_table_name('g_apply',$user_id);
		$this->query("update $table set remark='$name' where g_id=$g_id");
	}
	function updatExchangeMark($user_id,$g_id,$name){
		//$table="g_exchange".$user_id%100;
		$table = SystemProperties::get_table_name('g_exchange',$user_id);
		$this->query("update $table set remark='$name' where g_id=$g_id");
	}
	function findMark($user_id,$g_id,$type){
		if($type==1){
			//$table="g_apply".$user_id%100;
			$table = SystemProperties::get_table_name('g_apply',$user_id);
		}else{
			//$table="g_exchange".$user_id%100;
			$table = SystemProperties::get_table_name('g_exchange',$user_id);
		}
		$data=$this->query("select remark from  $table  mark where g_id=$g_id");
		return $data[0]['mark']['remark'];
	}
	function updateInfoSent($change,$sid,$in_list){
		if ($change){
			$tname = 'g_exchange0';
		}else {
			$tname = 'g_apply0';
		}
		$sid = intval($sid);
		$in_list = intval($in_list);
		$this->query("update $tname set remark = '{$in_list}' where g_id = {$sid} ");
		//echo "update $tname set remark = '{$in_list}' where g_id = {$sid} ";
	}
	
	
	function listAllShareGroup(){
		$data=$this->query("select * from g_sharegroups where 1 order by `order` ");
		return $data;
	}

	
	
	function shareGroupAdd($order,$pic){
		$pic = mysql_escape_string($pic);
		$order = intval($order);
		$this->query("insert into g_sharegroups (`pids`,`order`,`pic`)values('','{$order}','{$pic}')");
	}
	function shareGroupAddProduct($guid,$pid){
		if (empty($guid)|| empty($pid)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pid = intval($pid);
		$data=$this->query("select * from g_sharegroups where id='$guid'");
		if (empty($data)){
			return ;
		}
		$pids = explode(',',$data[0]['g_sharegroups']['pids']);
		$pids[] = $pid;
		$pids = array_unique($pids);
		$guest_pids = join(',',$pids);
		$data=$this->query("update g_sharegroups set `pids`='$guest_pids'  where id='$guid'");
		return $data;

	}
	function shareGroupDeleteProduct($guid,$pid){
		if (empty($guid)|| empty($pid)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pid = intval($pid);
		$data=$this->query("select * from g_sharegroups where id='$guid'");
		if (empty($data)){
			return ;
		}
		$pids = explode(',',$data[0]['g_sharegroups']['pids']);
		foreach ($pids as $k=>$v){
			if ($v==$pid){
				unset($pids[$k]);
			}
		}
		$pids = array_unique($pids);
		$guest_pids = join(',',$pids);
		$data=$this->query("update g_sharegroups set `pids`='$guest_pids'  where id='$guid'");
		return $data;

	}
	function shareGroupChangeOrder($guid,$pass){
		if (empty($guid)|| empty($pass)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pass = intval($pass);
		$this->query("update g_sharegroups set `order`='{$pass}' where `id`='{$guid}'");
	}
	function shareGroupDelete($guid){
	    if (empty($guid)){
	        return ;
	    }
	    $this->query("delete from g_sharegroups where `id`='{$guid}'");	    
	}	
	
	
	////////////
	function listAllGuest(){
		$data=$this->query("select * from g_logins where isguest = 1");
		return $data;
	}
	function guestAdd($guid,$pass){
		if (empty($guid)|| empty($pass)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pass = mysql_escape_string(md5($pass));
		$this->query("insert into g_logins (`g_name`,`g_password`)values('{$guid}','{$pass}')");
	}
	function guestAddProduct($guid,$pid){
		if (empty($guid)|| empty($pid)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pid = intval($pid);
		$data=$this->query("select * from g_logins where isguest = 1 and `g_name`='$guid'");
		if (empty($data)){
			return ;
		}
		$pids = explode(',',$data[0]['g_logins']['guest_pids']);
		$pids[] = $pid;
		$pids = array_unique($pids);
		$guest_pids = join(',',$pids);
		$data=$this->query("update g_logins set `guest_pids`='$guest_pids'  where isguest = 1 and `g_name`='$guid'");
		return $data;

	}
	function guestDeleteProduct($guid,$pid){
		if (empty($guid)|| empty($pid)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pid = intval($pid);
		$data=$this->query("select * from g_logins where isguest = 1 and `g_name`='$guid'");
		if (empty($data)){
			return ;
		}
		$pids = explode(',',$data[0]['g_logins']['guest_pids']);
		foreach ($pids as $k=>$v){
			if ($v==$pid){
				unset($pids[$k]);
			}
		}
		$pids = array_unique($pids);
		$guest_pids = join(',',$pids);
		$data=$this->query("update g_logins set `guest_pids`='$guest_pids'  where isguest = 1 and `g_name`='$guid'");
		return $data;

	}
	function guestChangePassword($guid,$pass){
		if (empty($guid)|| empty($pass)){
			return ;
		}
		$guid = mysql_escape_string($guid);
		$pass = mysql_escape_string(md5($pass));
		$this->query("update g_logins set `g_password`='{$pass}' where `g_name`='{$guid}'");
	}
	function guestDelete($guid){
	}
	
	function listAllPost($start=0,$count=8){
		$start = intval($start);
		$count = intval($count);
		if (SystemProperties::$platform=='renren'){
			$data = $this->query("select `g_timesplit_logs`.*,u.`g_name`,u.`g_head`,u.`g_uid`,p.`g_name` as `p_name` from  `g_timesplit_logs` left join `g_users` u on `user_id`=`g_id` left join g_products p on p.g_id = `product_id`  where  `post_url` IS NOT NULL order by seqid desc limit $start,$count");
		}else if (SystemProperties::$platform=='yoka' || SystemProperties::$platform=='myspace'){
			$data = $this->query("select `g_apply0`.*,`g_apply0`.g_id as seqid,u.`g_name`,u.`g_head`,u.`g_uid`,p.`g_id` as `product_id`,p.`g_name` as `p_name` from  `g_apply0` inner join `g_users` u on u.`g_id`=`g_apply0`.`user_id` inner join g_products p on p.g_id = `g_apply0`.`product`  where `post_url` IS NOT NULL order by `g_apply0`.g_id desc limit $start,$count");
		}

		if (empty($data[0])){
			return 0;
		}else {
			$ret = array();
			foreach ($data as $da){
				if (!empty($da['g_timesplit_logs'])){
					$ret[] = array_merge($da['g_timesplit_logs'],$da['u'],$da['p']);
				}
				if (!empty($da['g_apply0'])){
					$ret[] = array_merge($da['g_apply0'],$da['u'],$da['p']);
				}
			}
			return $ret;
		}
	}
	function updatePostGood($sid,$in_list){
		$sid = intval($sid);
		$in_list = intval($in_list);
		if (SystemProperties::$platform=='renren'){
			$this->query("update g_timesplit_logs set is_good_post = '{$in_list}' where seqid = {$sid} ");
		}else if (SystemProperties::$platform=='yoka'||SystemProperties::$platform=='myspace'){
			$this->query("update g_apply0 set is_good_post = '{$in_list}' where g_id = {$sid} ");
		}
		//echo "update $tname set remark = '{$in_list}' where g_id = {$sid} ";
	}
	function updateConfig($key,$value){
		$key =mysql_escape_string($key);
		$value =mysql_escape_string($value);
		$sql = "update `g_config` set `value`='$value' where `key` = '$key' ";
		$this->query($sql);
	}
	function getConfig($key){
		$key =mysql_escape_string($key);
		$sql = "select `value` from  `g_config` where `key` = '$key' ";
		$data = $this->query($sql);
		if (!empty($data[0]['g_config']['value'])){
			return $data[0]['g_config']['value'];
		}else {
			return '';
		}
	}	
	
	function importApplyOKUser(){
		if (SystemProperties::$platform!='renren'){
			return ;
		}
		$sql = "select product_id,user_id,time_start_id from `g_timesplit_logs` where is_luck=1";
		$data = $this->query($sql);
		foreach ($data as $da){
			$d = $da['g_timesplit_logs'];
			$sql = "select user_id from g_apply0 where user_id={$d['user_id']} and product={$d['product_id']} and g_img = '{$d['time_start_id']}'";
			$t = $this->query($sql);
			if (empty($t)){
				$sql = "insert into g_apply0 (user_id,product,g_time,g_img,g_message,g_view,g_status,g_jiazhi) values({$d['user_id']},{$d['product_id']},now(),'{$d['time_start_id']}','N',1,1,0)";
				$temp = $this->query($sql);			
			}
		}
	}
	function getAllUserCount() {
	    $sql = 'select count(1) as total from  g_users ';
	    $data = $this->query($sql);
	    return $data[0][0]['total'];
	}	
	function listCountData() {
	    $sql = 'select * from  daily_count order by date desc;';
	    $data = $this->query($sql);
	    return $data;
	}
	function listCutePigData($type = 'pig'){
	    $sql = 'SELECT time as d, count(1) as c FROM `cutepig_user_log` WHERE type = "'.substr($type, 0 ,8).'" GROUP BY time';
	    $data = $this->query($sql);
	    return $data;
	}
	function listCutePigType() {
	    $sql = 'SELECT distinct type FROM `cutepig_user_log` WHERE 1';
	    $data = $this->query($sql);
	    $ret = array();
	    foreach ($data as $da) {
	        $ret[] = $da['cutepig_user_log']['type'];
	    }
	    return $ret;	    
	}
	
	function listAllBlogData(){
	    $sql = 'SELECT * FROM `user_submit_blogs` b inner join g_users u on u.g_id = b.uid order by b.id desc';
	    $data = $this->query($sql);
	    return $data;
	}
	
	function check_is_in_blacklist($uid) {
	    $blacklist_ids = $this->getConfig('blacklist_ids');
		$t = preg_match_all('/([0-9]+)/', $blacklist_ids, $ma);
		
		if (!empty($ma[1]) && in_array($uid, $ma[1])){
		    return true;
		}
		

		return false;
	}	

	function get_blacklist() {
	    $blacklist_ids = $this->getConfig('blacklist_ids');
		$t = preg_match_all('/([0-9]+)/', $blacklist_ids, $ma);
		$all = empty($ma[1])?array():$ma[1];
		$all = array_merge(array_unique($all));
		return $all;
	}	
	function add_blacklist($uid) {
	    $blacklist_ids = $this->getConfig('blacklist_ids');
		$t = preg_match_all('/([0-9]+)/', $blacklist_ids, $ma);
		$all = empty($ma[1])?array():$ma[1];
		$all[] = $uid;
		$all = array_merge(array_unique($all));
		$all_str = join(',', $all);
		$this->updateConfig('blacklist_ids', $all_str);
	}
	function del_blacklist($uid) {
	    $blacklist_ids = $this->getConfig('blacklist_ids');
		$t = preg_match_all('/([0-9]+)/', $blacklist_ids, $ma);
		$all = empty($ma[1])?array():$ma[1];
		foreach ($all as $k=>$v) {
		    if (intval($v) == intval($uid)) {
		        unset($all[$k]);
		    }
		}
		$all = array_merge(array_unique($all));
		$all_str = join(',', $all);
		$this->updateConfig('blacklist_ids', $all_str);	    
	}
	
	
	/**
	 * fill product info for list
	 */
	function _fillProductInfo($data) {
	    if (empty($data)) {
	        return array();
	    }
	    $zhuan_ids = array();
	    $huan_ids = array();
	    foreach ($data as $da) {
	        $d = $da['g_lucks'];
	        if ($d['how_get'] == 'zhuan') {
	            $zhuan_ids[] = $d['pid'];
	        } else if ($d['how_get'] == 'huan') {
	            $huan_ids[] = $d['pid'];
	        }	        
	    }
        $zhuan_info = $this->getPInfo($zhuan_ids, 'g_products');
        $huan_info = $this->getPInfo($huan_ids, 'g_changes');
	    foreach ($data as $k=>$da) {
	        $d = $da['g_lucks'];
	        if ($d['how_get'] == 'zhuan') {
	            $data[$k]['g_lucks']['product_info'] = $zhuan_info[$d['pid']];
	        } else if ($d['how_get'] == 'huan') {
	            $data[$k]['g_lucks']['product_info'] = $huan_info[$d['pid']];
	        }	   
	        $data[$k]['g_lucks']['share_detail'] = json_decode($d['share_detail'],1);
	           
	    }	    
	    return $data;
	}	
	function getPInfo($ids, $table) {
	    
	    if (empty($ids)) {
	        return array();
	    }
	    foreach ($ids as $k=>$v) {
	        $ids[$k] = intval($v);
	    }
	    $ids = array_merge(array_unique($ids));
	    $sql = "select g_name,g_id,g_img,g_extra_url from `{$table}` where g_id in (".join(',',$ids).')';
	    $data = $this->query($sql);
	    $ret = array();
	    if (empty($data)) {
	        return $data;
	    } else {
	       foreach ($data as $da) {
	           $ret[$da[$table]['g_id']] = $da[$table];
	       }
	    }
	    return $ret;
	}	
}